package com.example.sql;

import static org.junit.Assert.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class SqlFZ {

	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

	private String sql = "select abc, sum(bsb), (select t.pid , (select p.name from person p) from student t,(select * from bbs) o where o.pid = t.pid ) from test t ,(select * from  cat tc)  where t.b=tc.b";
	
	
	

	public int test002(String sqlsss){
		Stack<Character> stac = new Stack<Character>();
		 String sqlTest = sqlsss.toLowerCase();
		 char[] sqlChar = sqlTest.toCharArray();
		 int indexFrom = sqlTest.indexOf("from");
		 int x,y,result=0;
		 for(int a=0;a<sqlChar.length;a++){
			if(sqlChar[a]=='('){
				stac.push(sqlChar[a]);
				x=a;
			}
			
			if(sqlChar[a]==')'){
				stac.pop();
				y=a;
				if(indexFrom<y){
					sqlTest = sqlTest.replaceFirst("from","");
					int z = test002(sqlTest);
					if(z!=0){
						return z+4;
					}
				}
				
			}
			if(stac.size()==0 && a==indexFrom){
				//System.out.println(sqlsss.substring(a));
				result = a;
				break;
			}
		 }
		 return result;
	}
	
	public String  getFrom(String psSql){
		Stack<Character> stac = new Stack<Character>();
		 String sqlTest = psSql.toLowerCase();
		 char[] sqlChar = sqlTest.toCharArray();
		 
		 int indexFrom = sqlTest.indexOf("from");
		 String result= "";
		 
		 for(int a=0;a<sqlChar.length;a++){
			if(sqlChar[a]=='('){
				stac.push(sqlChar[a]);
			}
			
			if(sqlChar[a]==')'){
				stac.pop();
				if(indexFrom<a){
					sqlTest = sqlTest.replaceFirst("from","");
					result = getFrom(sqlTest);
					break;
				}
				
			}
			if(stac.size()==0 && a==indexFrom){
				result = sqlTest;
				break;
			}
		 }
		 return result;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
